from collections import deque
import heapq


"""
解压可迭代对象赋值给多个变量
    1. 通过*号操作符实现
    2. *号操作符对应的变量永远是一个列表
    3. for循环中, 先提取单个元素, 然后再解压元素
"""
def unpack_iterable():
    record = (1, 2, 3, 4, 5)
    first, *middle, last = record
    print(first)
    print(middle)
    print(last)

    record1 = [
        ("hello", 1, 2),
        ("world", 3, 4, 5 ),
        ("peter", 6, 7, 8, 9),
    ]
    for tag, *args in record1:
        print(f"tag: {tag}, args: {args}")


"""
查找最大或最小的N个元素
    1. 通过heapq模块实现
    2. heapq模块提供了一个堆排序算法
    3. heapq.nlargest()和heapq.nsmallest()方法
"""
def nlargest_nsmallest_test():
    # 最大或者最小的N个元素
    nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    print(heapq.nlargest(3, nums))
    print(heapq.nsmallest(3, nums))

    # 指定比较的键值
    data = [
        {"name": "tom", "age": 20},
        {"name": "jerry", "age": 30},
        {"name": "peter", "age": 25},
    ]
    print(heapq.nsmallest(2, data, key=lambda x: x["age"]))
    print(heapq.nlargest(2, data, key=lambda x: x["age"]))

    # 最大最小值
    print(max(data, key=lambda x: x["age"]))
    print(max((1, 2), (3, 4), key=lambda x: x[1]))

    #排序和切片结合
    print(sorted(data, key=lambda x: x["age"], reverse=True)[:2])



"""
队列：可以固定队列的大小
    1. 通过deque模块实现
    2. 先进先出
    3. 队列的头部是最早添加的元素，队列的末尾是最新添加的元素
"""
def deque_test():
    queue = deque(maxlen=5)
    queue.append(1)
    queue.extend([3, 4])
    print(queue)
    print(queue.pop())


"""
优先级队列：
    1. 通过heapq模块实现
    2. 首先比对优先级，相同优先级按元素的插入顺序排序
    3. 数值越高优先级越高
"""
class PriorityQueue:
    def __init__(self):
        self._queue = []
        self._index = 0

    def push(self, item, priority):
        heapq.heappush(self._queue, (-priority, self._index, item))
        self._index += 1

    def pop(self):
        return heapq.heappop(self._queue)[-1]


nlargest_nsmallest_test()































